<?php

/**
 * @author игорь
 * @copyright 2008
 */

/**
 * Page
 * 
 * @package meow.net.ru SVN
 * @author igor.barkowsky@gmail.com
 * @copyright 2009
 * @version $Id$
 * @access public
 */
class Page
{
	var $db;
	var $tree;
	var $content;
	var $smarty;
	var $id;
	var $module;
	var $dir;
	var $template;
	var $alias;
	var $full_alias;
	var $over;
	var $adress_string;
	/**
	 * Page::__construct()
	 * 
	 * @param integer $id
	 * @return void
	 */
	function __construct($id = 0)
	{
		global $smarty, $db;
		$this->db 					= $db;
		$this->tree 				= $this->db->pfx."site_tree";
		$this->content 				= $this->db->pfx."site_content";
		$this->smarty 				=$smarty;
		$this->id 					= $id;
		$this->info 				= $this->getPage($this->id);
		$this->menu 				= $this->getMenu($this->id);
		$this->dir 					= $this->info['dir'];
		$this->module 				= $this->info['module'];
		$this->template 			= $this->info['template'];
		$this->alias 				= $this->info['alias'];
		$this->full_alias 			= $this->getFullAlias($this->id);
		$this->info['full_alias'] 	= $this->full_alias;
        $this->adress_string 		= $this->createAdress();
	}
	/**
	 * Page::getPage()
	 * 
	 * @param integer $id
	 * @param integer $status
	 * @return array || false on error
	 */
	function getPage($id = 0,$status = 0)
	{
		$page = $this->db->fetch_one("SELECT * FROM $this->content AS c,$this->tree AS t WHERE t.id='".mysql_real_escape_string($id)."' AND c.tree_id=t.id AND t.status >= '".mysql_real_escape_string($status)."'",MYSQL_ASSOC);
		if($page != false) return $page;
		else return false;
	}
	/**
	 * Page::getSubFor()
	 * 
	 * @param integer $parent
	 * @param integer $status
	 * @param integer $lim_from
	 * @param integer $per_page
	 * @return array || false on error
	 */
	function getSubFor($parent = 0,$status = 0,$lim_from = 0,$per_page = 0)
	{
		if(intval($per_page) != 0)
		{
			$limit = "LIMIT $lim_from,$per_page";
		}
		else $limit = "";
		$pages = $this->db->fetch_array("SELECT * FROM $this->content AS c,$this->tree AS t WHERE t.pid='".intval($parent)."' AND t.id <> '0' AND c.tree_id=t.id AND t.status >= '".intval($status)."' ORDER BY order_num $limit",MYSQL_ASSOC);
		if($pages != false and !empty($pages)) return $pages;
		else return false;
	}
	/**
	 * Page::getMenu()
	 * 
	 * @param integer $parent
	 * @param integer $display
	 * @return array || false on error
	 */
	function getMenu($parent = 0,$display = 0)
	{
		$menu = $this->db->fetch_array("SELECT t.id,t.pid,t.alias,t.module,t.type,t.dir,c.tree_id,c.title,c.menu_title FROM ".$this->tree." AS t, ".$this->content." AS c WHERE t.pid='".$parent."' AND c.tree_id=t.id AND t.status>='".$display."'",MYSQL_ASSOC);
		if($menu!=false)
		{
			foreach($menu as $k => $v)
			{
				$menu[$k]['full_alias'] = $this->getFullAlias($v['id']);
			}
			return $menu;
		} 
		else return false;
	}
	/**
	 * Page::getFullAlias()
	 * 
	 * @param integer $id
	 * @return string
	 */
	function getFullAlias($id = 0)
	{
		$alias = SITE_URL.'';
		if(intval($id) != 0)
		{
			$item = $this->db->fetch_one("SELECT t.pid,t.type,t.alias FROM ".$this->tree." AS t WHERE t.id='".intval($id)."'");
			$alias = $item['alias'].($item['type'] == '1'?'/':'.html');
			if($item['pid'] != '0') $alias = $this->getFullAlias($item['pid']).$alias;
		}
		return $alias;
	}
    /**
     * Page::fetchPath()
     * 
     * @param array $path
     * @return array
     */
    function fetchPath($path = array())
    {
        $path_level = count($path);
        $max = $path_level - 1;
        
        $thismod = $path[$max];
        $mod_path = array();
        if (isset($thismod['over']))
        {
            $thispath = explode("/", $thismod['over']);
            if (!empty($thispath))
            {
                foreach ($thispath as $t=>$p)
                {
                    if ($p != '')
                    {
                        $mod_path[] = $p;
                    } 
                }
            }
        }
        return $mod_path;
    }
	/**
	 * Page::createContent()
	 * 
	 * @return void
	 */
	function createContent()
	{
		global $db,$smarty,$user;
		/** START 	Создание линамического контента и отображение **/
		/** скин для сайта **/
		$this->skin="index";//TODO: подгружать соответствующий шаблон и стиль для определенной страницы
		/** ПОДКЛЮЧЕНИЕ МОДУЛЯ для запрошенной страницы **/
		include_once(ROOT_DIR.MOD_DIR.$this->dir."/".$this->module.MOD_EXT);
		$this->smarty->assign("adress_string",$this->adress_string);
		/** разбор шаблона контента с примененим данных, полученных от модуля **/
		$this->module_content=$this->smarty->fetch("templates/".$this->template.TMPL_EXT);
		/** END 	Создание линамического контента и отображение **/
	}
    /**
     * Page::createAdress()
     * 
     * @return array
     */
    function createAdress()
    {
    	$adres_str = array();
        $adr_path = $this->getParents($this->info['tree_id']);

        $adres_str[0]['title'] = 'Переход на главную страницу';
        $adres_str[0]['menu_title'] = 'Главная';
        $adres_str[0]['alias'] = '/';

        $i = 1;
        if ($this->info['tree_id'] != '0')
        {
            foreach($adr_path as $pp => $vv)
            {
                $adres_str[$i]['title'] = htmlspecialchars($vv['title'], ENT_QUOTES);
                $adres_str[$i]['menu_title'] = $vv['menu_title'];
                $adres_str[$i]['alias'] = '/'.$this->getFullAlias($vv['id']);
                $i++;
            }
        }
        return $adres_str;
    }
    /**
     * Page::appendAddress()
     * 
     * @param array $adr
     * @return array
     */
    function appendAddress ($adr)
    {
        if(!empty($adr))
        {
	        foreach($adr as $n => $part_of_adress)
	        {
		        $this->adress_string = array_merge($this->adress_string,$part_of_adress);
	        }
        }
        return $this->adress_string;
    }
    /**
     * Page::getParents()
     * 
     * @param integer $id
     * @return array
     */
    function getParents ($id = 0)
    {
        $path = array();
        $page = $this->db->fetch_one("SELECT t.id, t.pid, c.menu_title, c.title FROM $this->content as c, $this->tree as t WHERE t.id = '$id' and c.tree_id = t.id");
        if ($page != false and !empty($page)){$path[] = $page;}
        if($page != false and !empty($page) && intval($page['pid']) != 0)
        {
            $path = array_merge($this->getParents($page['pid']), $path);
        }
        return $path;
    }
	/**
	 * Page::getChildsList()
	 * 
	 * @param integer $id
	 * @param integer $status
	 * @return array
	 */
	function getChildsList ($id = 0,$status = 0)
	{
		$childs = array();
        $childs_data = $this->db->fetch_list("SELECT t.id FROM $this->tree as t WHERE t.id <> '0' AND t.pid = '$id' AND t.status >= '$status'");
        if ($childs_data != false and !empty($childs_data))
		{
			$childs = $childs_data;
			foreach($childs_data as $k=>$v)
			{
				$childs = array_merge($childs,$this->getChildsList($v,$status));
			}
		}
        return $childs;
	}
}

class NewsPage extends Page{}

class AdminPage extends Page
{
	function __construct($id = 0)
	{
		global $smarty, $db;
		$this->db=$db;
		$this->tree= $this->db->pfx."admin_tree";
		$this->content= $this->db->pfx."admin_content";
		$this->smarty=$smarty;
		$this->id=$id;
		$this->info = $this->getPage($this->id);
		$this->menu = $this->getMenu($this->id);
		$this->dir = $this->info['dir'];
		$this->module = $this->info['module'];
		$this->template = $this->info['template'];
		$this->alias = $this->info['alias'];
		$this->full_alias = $this->getFullAlias($this->id);
		$this->info['full_alias'] = $this->full_alias;
        $this->adress_string = $this->createAdress();
	}
	function getMenu($parent=0,$display=0)
	{
		$menu = $this->db->fetch_array("SELECT t.id,t.pid,t.alias,t.module,t.type,t.dir,c.title,c.menu_title FROM ".$this->tree." AS t, ".$this->content." AS c WHERE t.pid='".$parent."' AND c.tree_id=t.id AND t.status>='".$display."'",MYSQL_ASSOC);
		if($menu!=false)
		{
			foreach($menu as $k=>$v)
			{
				$menu[$k]['full_alias']=ADMIN_URL.$this->getFullAlias($v['id']);
			}
			return $menu;
		} 
		else return false;
	}
	function createContent()
	{
		global $db,$smarty,$user;
		/** START 	Создание линамического контента и отображение **/
		/** скин для сайта **/
		$this->skin="index";//TODO: подгружать соответствующий шаблон и стиль для определенной страницы
		/** ПОДКЛЮЧЕНИЕ МОДУЛЯ для запрошенной страницы **/
		include_once(ADMIN_DIR.MOD_DIR.$this->dir."/".$this->module.MOD_EXT);
		/** ПОДКЛЮЧЕНИЕ ИНФОРМАЦИОННОГО БЛОКА МОДУЛЯ для запрошенной страницы **/
		include_once(ADMIN_DIR.MOD_DIR.$this->dir."/info".MOD_EXT);
		/** Создание адресной строки */
		$this->smarty->assign("adress_string",$this->adress_string);
		/** разбор шаблона контента с примененим данных, полученных от модуля **/
		$this->module_content=$this->smarty->fetch("modules/".$this->dir.TMPL_DIR.$this->template.TMPL_EXT);
		/** END 	Создание линамического контента и отображение **/
	}
	/**
	 * AdminPage::getFullAlias()
	 * 
	 * @param integer $id
	 * @return
	 */
	function getFullAlias($id = 0)
	{
		$alias = ADMIN_URL.'';
		if(intval($id) != 0)
		{
			$item = $this->db->fetch_one("SELECT t.pid,t.type,t.alias FROM ".$this->tree." AS t WHERE t.id='".intval($id)."'");
			$alias = $item['alias'].($item['type'] == '1'?'/':'.html');
			if($item['pid'] != '0') $alias = $this->getFullAlias($item['pid']).$alias;
		}
		return $alias;
	}
}
?>